﻿#if NETSTANDARD
using Microsoft.Extensions.Options;
#endif
using PaySharp.Core;
using PaySharp.Core.Exceptions;
using PaySharp.Core.Request;
using PaySharp.Core.Utils;
using PaySharp.Qpay.Response;
using System.Threading.Tasks;

namespace PaySharp.Qpay
{
    /// <summary>
    /// QQ钱包网关
    /// </summary>
    public sealed class QpayGateway : BaseGateway
    {
        #region 私有字段

        private readonly Merchant _merchant;

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化QQ钱包网关
        /// </summary>
        /// <param name="merchant">商户数据</param>
        public QpayGateway(Merchant merchant)
            : base(merchant)
        {
            _merchant = merchant;
        }

#if NETSTANDARD

        /// <summary>
        /// 初始化QQ钱包网关
        /// </summary>
        /// <param name="merchant">商户数据</param>
        public QpayGateway(IOptions<Merchant> merchant)
            : this(merchant.Value)
        {
        }

#endif

        #endregion

        #region 属性

        public override string GatewayUrl { get; set; } = "https://qpay.qq.com";

        public new Merchant Merchant => _merchant;

 

        protected override string[] NotifyVerifyParameter => new string[]
        {
            "appid","trade_state", "mch_id", "fee_type"
        };

        #endregion

        #region 方法




        public override NotifyResult ValidateNotify()
        {
            NotifyResult result = new NotifyResult();
            GatewayData gatewayData = NotifyProcess.ReadNotifyData();
            var response = gatewayData.ToObject<NotifyResponse>(StringCase.Snake); 
            result.Source = HttpUtil.RequestType == "GET" ? NotifySource.Sync : NotifySource.Async;
            result.Type = NotifyType.UnknownNotify; 
            if (response.TradeState == "SUCCESS")
            {
                result.Type = NotifyType.PaySuccess;
            } 
            if (response.Sign != SubmitProcess.BuildSign(gatewayData, _merchant.Key))
            {
                result.Status = NotifyStatus.ValidateError;
            }
            else
            {
                result.Status = NotifyStatus.ValidateSuccess;
            }
            result.Response = response; 
            return result;

        }


        protected override void WriteSuccessFlag()
        {
            GatewayData gatewayData = new GatewayData();
            gatewayData.Add("return_code", "SUCCESS");
            HttpUtil.Write(gatewayData.ToXml());
        }

        protected override void WriteFailureFlag()
        {
            GatewayData gatewayData = new GatewayData();
            gatewayData.Add("return_code", "FAIL");
            HttpUtil.Write(gatewayData.ToXml());
        }


        public override TResponse Execute<TModel, TResponse>(Request<TModel, TResponse> request)
        {
            return SubmitProcess.Execute(_merchant, request, GatewayUrl);
        }

        #endregion
    }
}
